<template>
  <div class="analysis-container">
    <el-card class="card">
      <template #header>数据分析</template>

      <!-- 工位选择器 -->
      <div class="workstation-selector">
        <div class="selector-row">
          <div class="section-title">选择工位：</div>
          <el-select v-model="selectedWorkstation" placeholder="请选择工位" style="width: 200px;" :loading="loading"
            :disabled="loading || workstations.length === 0" @change="handleWorkstationChange">
            <el-option v-for="workstation in workstations" :key="workstation.id"
              :label="`${workstation.name} (${workstation.status === 'normal' ? '正常' : '异常'})`" :value="workstation.id">
            </el-option>
          </el-select>
        </div>
        <div v-if="loading" class="loading-text">正在加载工位数据...</div>
        <div v-else-if="workstations.length === 0" class="empty-text">暂无可分析的工位</div>
      </div>

      <!-- 选中工位信息显示区域 -->
      <div v-if="selectedWorkstation && currentWorkstation" class="workstation-info">
        <div class="section-title">
          <el-icon style="margin-right: 8px; color: #409eff;">
            <Monitor />
          </el-icon>
          工位号
          <span class="workstation-number">{{ currentWorkstation.name }}</span>
        </div>

        <el-row :gutter="16">
          <!-- 设备状态 -->
          <el-col :span="12">
            <el-card class="info-card">
              <template #header>设备状态</template>
              <el-descriptions :column="2" size="small"
                :label-style="{ width: '100px', textAlign: 'right', paddingRight: '8px' }"
                :content-style="{ textAlign: 'left', paddingLeft: '8px' }">
                <el-descriptions-item label="电源状态&nbsp; &nbsp; &nbsp; &nbsp;">
                  <span :class="getDeviceStatusClass(currentWorkstation.power)">
                    <el-icon style="margin-right: 4px;">
                      <Switch />
                    </el-icon>
                    <el-tag style="border: none;" :type="currentWorkstation.power ? 'success' : 'danger'" size="small">
                      {{ currentWorkstation.power ? '开启' : '关闭' }}
                    </el-tag>
                  </span>
                </el-descriptions-item>
                <el-descriptions-item label="灯光状态&nbsp; &nbsp; &nbsp; &nbsp;">
                  <span :class="getDeviceStatusClass(currentWorkstation.light)">
                    <el-icon style="margin-right: 4px;">
                      <Switch />
                    </el-icon>
                    <el-tag style="border: none;" :type="currentWorkstation.light ? 'success' : 'danger'" size="small">
                      {{ currentWorkstation.light ? '开启' : '关闭' }}
                    </el-tag>
                  </span>
                </el-descriptions-item>
                <el-descriptions-item label="继电器1状态">
                  <span :class="getDeviceStatusClass(currentWorkstation.relay1)">
                    <el-icon style="margin-right: 4px;">
                      <Switch />
                    </el-icon>
                    <el-tag style="border: none;" :type="currentWorkstation.relay1 ? 'success' : 'danger'" size="small">
                      {{ currentWorkstation.relay1 ? '开启' : '关闭' }}
                    </el-tag>
                  </span>
                </el-descriptions-item>
                <el-descriptions-item label="继电器2状态">
                  <span :class="getDeviceStatusClass(currentWorkstation.relay2)">
                    <el-icon style="margin-right: 4px;">
                      <Switch />
                    </el-icon>
                    <el-tag style="border: none;" :type="currentWorkstation.relay2 ? 'success' : 'danger'" size="small">
                      {{ currentWorkstation.relay2 ? '开启' : '关闭' }}
                    </el-tag>
                  </span>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>

          <!-- 传感器数据 -->
          <el-col :span="12">
            <el-card class="info-card">
              <template #header>传感器数据</template>
              <el-descriptions :column="2" size="small"
                :label-style="{ width: '100px', textAlign: 'right', paddingRight: '8px' }"
                :content-style="{ textAlign: 'left', paddingLeft: '8px' }">
                <el-descriptions-item label="温度&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;">
                  <span v-if="currentWorkstation.temperature"
                    :class="getTemperatureClass(currentWorkstation.temperature)">
                    <el-icon style="margin-right: 4px;">
                      <Thermometer />
                    </el-icon>
                    {{ currentWorkstation.temperature }}°C
                  </span>
                  <span v-else class="no-data">--</span>
                </el-descriptions-item>
                <el-descriptions-item label="湿度&nbsp;&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;">
                  <span v-if="currentWorkstation.humidity" :class="getHumidityClass(currentWorkstation.humidity)">
                    <el-icon style="margin-right: 4px;">
                      <WaterDrop />
                    </el-icon>
                    {{ currentWorkstation.humidity }}%
                  </span>
                  <span v-else class="no-data">--</span>
                </el-descriptions-item>
                <el-descriptions-item label="烟雾浓度">
                  <span v-if="currentWorkstation.smokeScope" :class="getSmokeClass(currentWorkstation.smokeScope)">
                    <el-icon style="margin-right: 4px;">
                      <Cloud />
                    </el-icon>
                    {{ currentWorkstation.smokeScope }}%
                  </span>
                  <span v-else class="no-data">--</span>
                </el-descriptions-item>
                <el-descriptions-item label="火焰检测">
                  <span v-if="currentWorkstation.flameScope !== undefined"
                    :class="getFlameClass(currentWorkstation.flameScope)">
                    <el-icon style="margin-right: 6px;">
                      <Fire />
                    </el-icon>
                    {{ currentWorkstation.flameScope > 50 ? '检测到火焰' : '正常' }}
                  </span>
                  <span v-else class="no-data">--</span>
                </el-descriptions-item>
                <el-descriptions-item label="光照强度">
                  <span v-if="currentWorkstation.lightIntensity"
                    :class="getLightClass(currentWorkstation.lightIntensity)">
                    <el-icon style="margin-right: 4px;">
                      <Sunny />
                    </el-icon>
                    {{ currentWorkstation.lightIntensity }} %
                  </span>
                  <span v-else class="no-data">--</span>
                </el-descriptions-item>
                <el-descriptions-item label="热敏检测">
                  <span v-if="currentWorkstation.heatScope" :class="getHeatClass(currentWorkstation.heatScope)">
                    <el-icon style="margin-right: 4px;">
                      <HotWater />
                    </el-icon>
                    {{ currentWorkstation.heatScope }}°C
                  </span>
                  <span v-else class="no-data">--</span>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
        </el-row>

        <!-- 用户信息 -->
        <el-row :gutter="16" style="margin-top: 16px;">
          <el-col :span="24">
            <el-card class="info-card">
              <template #header>用户信息</template>
              <el-descriptions :column="2" size="small"
                :label-style="{ width: '120px', textAlign: 'right', paddingRight: '8px' }"
                :content-style="{ textAlign: 'left', paddingLeft: '8px' }">
                <el-descriptions-item label="使用者用户名">
                  <span class="user-info-item">
                    <el-icon style="margin-right: 6px; color: #409eff;">
                      <User />
                    </el-icon>
                    {{ currentWorkstation.username || '--' }}
                  </span>
                </el-descriptions-item>
                <el-descriptions-item label="使用者姓名">
                  <span class="user-info-item">
                    <el-icon style="margin-right: 6px; color: #67c23a;">
                      <User />
                    </el-icon>
                    {{ currentWorkstation.realName || '--' }}
                  </span>
                </el-descriptions-item>
                <el-descriptions-item label="最后更新时间">
                  <span class="user-info-item">
                    <el-icon style="margin-right: 6px; color: #e6a23c;">
                      <Clock />
                    </el-icon>
                    {{ currentWorkstation.modifyTime || '--' }}
                  </span>
                </el-descriptions-item>
                <el-descriptions-item label="工位状态&nbsp; &nbsp;">
                  <span class="user-info-item">
                    <el-icon style="margin-right: 6px;"
                      :style="{ color: currentWorkstation.status === 'normal' ? '#67c23a' : '#e6a23c' }">
                      <component :is="currentWorkstation.status === 'normal' ? CheckCircle : Warning" />
                    </el-icon>
                    <el-tag :type="currentWorkstation.status === 'normal' ? 'success' : 'warning'" size="small">
                      {{ currentWorkstation.status === 'normal' ? '正常' : '异常' }}
                    </el-tag>
                  </span>
                </el-descriptions-item>
              </el-descriptions>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 图表占位符 -->
      <div v-if="selectedWorkstation && currentWorkstation" class="charts-placeholder">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <span>数据可视化</span>
              <el-button type="text" @click="showCharts = !showCharts">
                {{ showCharts ? '隐藏图表' : '显示图表' }}
              </el-button>
            </div>
          </template>

          <div v-if="showCharts" class="charts-area">
            <el-alert title="图表功能开发中" description="温湿度曲线图、光照强度图等图表功能正在开发中，敬请期待！" type="info" :closable="false"
              style="margin-bottom: 16px;">
            </el-alert>

            <el-row :gutter="16">
              <el-col :span="24">
                <div class="chart-placeholder">
                  <el-icon size="64" color="#909399">
          <i class="el-icon-data-analysis"></i>
        </el-icon>
                  <p>图表展示区域</p>
                  <p style="font-size: 12px; color: #c0c4cc;">选择工位后可查看数据趋势图表</p>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import request from '@/utils/request.js'
import {
  Thermometer,
  WaterDrop,
  Cloud,
  Fire,
  Sunny,
  HotWater,
  Switch,
  Light,
  ElectricMeter,
  User,
  Clock,
  CheckCircle,
  Warning,
  Monitor
} from '@element-plus/icons-vue'

// 路由对象
const route = useRoute()

// 工位数据
const workstations = ref([])

// 实验室数据
const labData = ref({})

// 加载状态
const loading = ref(false)

// 当前选中的工位ID
const selectedWorkstation = ref(null)

// 图表显示状态
const showCharts = ref(false)

// 当前选中工位的引用
const currentWorkstation = computed(() => {
  if (!selectedWorkstation.value) return null
  return workstations.value.find(w => w.id === selectedWorkstation.value)
})

// 获取工位数据
const fetchWorkstationData = async () => {
  try {
    loading.value = true
    const response = await request.get('/env/admin/query')
    const resData = response.data

    console.log("工位数据返回结果:", resData)

    if (resData.state === 200 && resData.data) {
      // 赋值实验室基础数据
      Object.assign(labData.value, resData.data)

      // 清空之前的工位数据
      workstations.value.length = 0

      // 处理工位数据，将后端格式转换为前端格式
      if (resData.data.workstations && resData.data.workstations.length > 0) {
        const processedWorkstations = resData.data.workstations.map(backendWorkstation => ({
          id: backendWorkstation.id,
          name: backendWorkstation.workstationCode,
          code: backendWorkstation.workstationCode,
          status: backendWorkstation.workstationStatus,
          // 设备状态
          power: backendWorkstation.powerStatus === 1,
          light: backendWorkstation.lightStatus === 1,
          relay1: backendWorkstation.relayNum1Status === 1,
          relay2: backendWorkstation.relayNum2Status === 1,
          // 传感器数据
          temperature: backendWorkstation.temperature,
          humidity: backendWorkstation.humidity,
          smokeScope: backendWorkstation.smokeScope,
          flameScope: backendWorkstation.flameScope,
          lightIntensity: backendWorkstation.lightIntensity,
          heatScope: backendWorkstation.heatScope,
          // 用户信息
          curUserId: backendWorkstation.curUserId,
          username: backendWorkstation.username,
          realName: backendWorkstation.realName,
          modifyTime: backendWorkstation.modifyTime
        }))

        workstations.value.push(...processedWorkstations)

        console.log("处理后的工位列表数据:", workstations.value)

        // 如果有工位数据，默认选中第一个或从路由参数指定的工位
        if (workstations.value.length > 0) {
          // 检查路由参数中是否有指定的工位ID
          const routeWorkstationId = route.query.workstationId
          if (routeWorkstationId && workstations.value.some(w => w.id == routeWorkstationId)) {
            selectedWorkstation.value = parseInt(routeWorkstationId)
          } else if (!selectedWorkstation.value) {
            selectedWorkstation.value = workstations.value[0].id
          }
        }
      }
    } else {
      ElMessage.error(resData.message || '获取工位数据失败')
    }
  } catch (error) {
    console.error('获取工位数据失败:', error)
    ElMessage.error('获取工位数据失败，请稍后重试')
  } finally {
    loading.value = false
  }
}

// 处理工位选择变更
const handleWorkstationChange = (workstationId) => {
  console.log('选择工位:', workstationId)
  // 可以在这里添加切换工位时的额外逻辑
}

// 监听路由参数变化
watch(() => route.query.workstationId, (newWorkstationId) => {
  if (newWorkstationId && workstations.value.length > 0) {
    const workstationId = parseInt(newWorkstationId)
    if (workstations.value.some(w => w.id === workstationId)) {
      selectedWorkstation.value = workstationId
    }
  }
})

// 美化样式类
const getTemperatureClass = (temperature) => {
  if (temperature < 18) return 'sensor-value cold'
  if (temperature > 28) return 'sensor-value hot'
  return 'sensor-value normal'
}

const getHumidityClass = (humidity) => {
  if (humidity < 30) return 'sensor-value dry'
  if (humidity > 70) return 'sensor-value wet'
  return 'sensor-value normal'
}

const getSmokeClass = (smoke) => {
  if (smoke > 80) return 'sensor-value danger'
  if (smoke > 50) return 'sensor-value warning'
  return 'sensor-value normal'
}

const getFlameClass = (flame) => {
  return flame > 50 ? 'sensor-value danger' : 'sensor-value normal'
}

const getLightClass = (light) => {
  if (light < 100) return 'sensor-value dark'
  if (light > 800) return 'sensor-value bright'
  return 'sensor-value normal'
}

const getHeatClass = (heat) => {
  if (heat > 60) return 'sensor-value hot'
  if (heat < 10) return 'sensor-value cold'
  return 'sensor-value normal'
}

const getDeviceStatusClass = (status) => {
  return status ? 'device-status active' : 'device-status inactive'
}

// 组件挂载时获取数据
onMounted(() => {
  fetchWorkstationData()
})
</script>

<style scoped>
.analysis-container {
  padding: 20px;
}

.card {
  width: 100%;
}

.section-title {
  font-weight: 600;
  font-size: 16px;
  color: #303133;
  margin-top: 10px;
  margin-bottom: 10px;
}

.workstation-selector {
  margin-bottom: 24px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border-left: 4px solid #409eff;
}

.selector-row {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: 12px;
  margin-bottom: 1px;
}

.loading-text,
.empty-text {
  margin-top: 8px;
  font-size: 12px;
  color: #909399;
}

.empty-text {
  color: #f56c6c;
}

.workstation-info {
  margin-bottom: 24px;
}

.info-card {
  height: 100%;
}

.charts-placeholder {
  margin-top: 24px;
}

.chart-card {
  height: 100%;
}

.charts-area {
  padding: 16px 0;
}

.chart-placeholder {
  height: 300px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  color: #909399;
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
}

.chart-placeholder p {
  margin-top: 8px;
  color: #909399;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .workstation-selector {
    padding: 12px;
  }

  .selector-row {
    flex-direction: column;
    align-items: flex-start;
    gap: 8px;
  }

  .section-title {
    margin-bottom: 8px;
  }

  .chart-placeholder {
    height: 250px;
  }

  .info-card {
    margin-bottom: 16px;
  }

  /* 在移动端将描述列表改为单列显示 */
  .info-card .el-descriptions {
    column-count: 1 !important;
  }

  .info-card .el-descriptions__label {
    width: 80px !important;
  }
}

/* 传感器数值美化样式 */
.sensor-value {
  font-size: 14px;
  font-weight: 600;
  padding: 4px 8px;
  border-radius: 6px;
  display: inline-flex;
  align-items: center;
  gap: 4px;
}

/* 温度样式 */
.sensor-value.cold {
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
}

.sensor-value.hot {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
}

.sensor-value.normal {
  color: #67c23a;
  background: rgba(103, 194, 58, 0.1);
}

/* 湿度样式 */
.sensor-value.dry {
  color: #e6a23c;
  background: rgba(230, 162, 60, 0.1);
}

.sensor-value.wet {
  color: #409eff;
  background: rgba(64, 158, 255, 0.1);
}

/* 烟雾样式 */
.sensor-value.danger {
  color: #f56c6c;
  background: rgba(245, 108, 108, 0.1);
  animation: pulse-danger 2s infinite;
}

.sensor-value.warning {
  color: #e6a23c;
  background: rgba(230, 162, 60, 0.1);
}

/* 火焰样式已在烟雾样式中定义 */

/* 光照样式 */
.sensor-value.dark {
  color: #606266;
  background: rgba(96, 98, 102, 0.1);
}

.sensor-value.bright {
  color: #e6a23c;
  background: rgba(230, 162, 60, 0.1);
}

/* 无数据样式 */
.sensor-value.no-data {
  color: #909399;
  font-style: italic;
}

/* 设备状态样式 */
.device-status {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  padding: 6px 12px;
  border-radius: 20px;
  font-size: 14px;
  font-weight: 500;
}

.device-status.active {
  background: rgba(103, 194, 58, 0.1);
  color: #67c23a;
  border: 1px solid rgba(103, 194, 58, 0.3);
}

.device-status.inactive {
  background: rgba(245, 108, 108, 0.1);
  color: #f56c6c;
  border: 1px solid rgba(245, 108, 108, 0.3);
}

/* 用户信息样式 */
.user-info-item {
  display: inline-flex;
  align-items: center;
  font-size: 14px;
  color: #606266;
}

/* 动画效果 */
@keyframes pulse-danger {

  0%,
  100% {
    opacity: 1;
  }

  50% {
    opacity: 0.7;
  }
}
</style>
